<template>
  <view class="test-page">
    <view class="header">
      <text class="title">WebSocket连接测试</text>
    </view>
    
    <view class="status-section">
      <text class="status-label">连接状态:</text>
      <text class="status-value" :class="connectionStatusClass">{{ connectionStatus }}</text>
    </view>
    
    <view class="button-section">
      <button @click="connectWebSocket" :disabled="isConnecting" class="connect-btn">
        {{ isConnecting ? '连接中...' : '连接WebSocket' }}
      </button>
      <button @click="disconnectWebSocket" :disabled="!isConnected" class="disconnect-btn">
        断开连接
      </button>
      <button @click="sendTestMessage" :disabled="!isConnected" class="send-btn">
        发送测试消息
      </button>
    </view>
    
    <view class="log-section">
      <text class="log-title">连接日志:</text>
      <scroll-view class="log-container" scroll-y="true">
        <text v-for="(log, index) in logs" :key="index" class="log-item">{{ log }}</text>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 数据
const isConnected = ref(false)
const isConnecting = ref(false)
const logs = ref([])
let ws = null

// 计算属性
const connectionStatus = computed(() => {
  if (isConnecting.value) return '连接中...'
  if (isConnected.value) return '已连接'
  return '未连接'
})

const connectionStatusClass = computed(() => {
  if (isConnecting.value) return 'status-connecting'
  if (isConnected.value) return 'status-connected'
  return 'status-disconnected'
})

// 添加日志
const addLog = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.push(`[${timestamp}] ${message}`)
  console.log(`[WebSocket Test] ${message}`)
}

// 连接WebSocket
const connectWebSocket = () => {
  if (isConnecting.value || isConnected.value) return
  
  isConnecting.value = true
  addLog('开始连接WebSocket...')
  
  const token = uni.getStorageSync('accessToken')
  if (!token) {
    addLog('错误: 未找到访问令牌')
    isConnecting.value = false
    return
  }
  
  const wsUrl = `wss://${NETWORK_CONFIG.API_BASE_URL}/ws?token=${token}`
  addLog(`连接URL: ${wsUrl}`)
  
  try {
    const socketTask = uni.connectSocket({
      url: wsUrl,
      success: () => {
        addLog('WebSocket连接请求发送成功')
      },
      fail: (error) => {
        addLog(`WebSocket连接请求失败: ${JSON.stringify(error)}`)
        isConnecting.value = false
      }
    })
    
    // 监听连接打开
    socketTask.onOpen(() => {
      addLog('WebSocket连接成功')
      isConnected.value = true
      isConnecting.value = false
      ws = socketTask
    })
    
    // 监听消息
    socketTask.onMessage((event) => {
      addLog(`收到消息: ${event.data}`)
    })
    
    // 监听连接关闭
    socketTask.onClose((event) => {
      addLog(`WebSocket连接关闭: ${event.code} - ${event.reason}`)
      isConnected.value = false
      isConnecting.value = false
      ws = null
    })
    
    // 监听连接错误
    socketTask.onError((error) => {
      addLog(`WebSocket连接错误: ${JSON.stringify(error)}`)
      isConnected.value = false
      isConnecting.value = false
      ws = null
    })
    
  } catch (error) {
    addLog(`创建WebSocket连接失败: ${error.message}`)
    isConnecting.value = false
  }
}

// 断开WebSocket
const disconnectWebSocket = () => {
  if (ws) {
    addLog('主动断开WebSocket连接')
    ws.close({
      code: 1000,
      reason: '用户主动断开'
    })
    ws = null
    isConnected.value = false
  }
}

// 发送测试消息
const sendTestMessage = () => {
  if (!ws || !isConnected.value) {
    addLog('错误: WebSocket未连接')
    return
  }
  
  const testMessage = {
    type: 'ping',
    timestamp: Date.now()
  }
  
  try {
    ws.send({
      data: JSON.stringify(testMessage),
      success: () => {
        addLog('测试消息发送成功')
      },
      fail: (error) => {
        addLog(`测试消息发送失败: ${JSON.stringify(error)}`)
      }
    })
  } catch (error) {
    addLog(`发送消息异常: ${error.message}`)
  }
}
</script>

<style scoped>
.test-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.status-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
}

.status-label {
  font-size: 16px;
  color: #666;
  margin-right: 10px;
}

.status-value {
  font-size: 16px;
  font-weight: bold;
}

.status-connected {
  color: #4CAF50;
}

.status-connecting {
  color: #FF9800;
}

.status-disconnected {
  color: #F44336;
}

.button-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.connect-btn, .disconnect-btn, .send-btn {
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.connect-btn {
  background: #4CAF50;
  color: white;
}

.connect-btn:disabled {
  background: #ccc;
}

.disconnect-btn {
  background: #F44336;
  color: white;
}

.disconnect-btn:disabled {
  background: #ccc;
}

.send-btn {
  background: #2196F3;
  color: white;
}

.send-btn:disabled {
  background: #ccc;
}

.log-section {
  background: white;
  border-radius: 8px;
  padding: 15px;
}

.log-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.log-container {
  height: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background: #f9f9f9;
}

.log-item {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  font-family: monospace;
}
</style>
